package seed.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import category.web.servlet.CategoryException;
import cn.itcast.servlet.BaseServlet;

import seed.domain.Message;
import seed.service.MessageException;
import seed.service.SeedService;
import user.domain.User;

public class AdminMessageServlet extends BaseServlet {
	 SeedService seedService = new SeedService ();

	public String messageGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, SQLException
		{
			
			List<Message> listmessage = seedService.listMessage();
			
			for(Message message: listmessage)
			{
				User user = seedService.getUserByUid(message.getUid());
				message.setUser(user);
			}
			
			request.setAttribute("listmessage", listmessage);
			return "f:adminjsps/admin/message/message.jsp";
		}
	

	public String messageDelete(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, SQLException
		{
			
{
			
			List<Message> listmessage = seedService.listMessage();
			
			for(Message message: listmessage)
			{
				User user = seedService.getUserByUid(message.getUid());
				message.setUser(user);
			}
			
			request.setAttribute("listmessage", listmessage);
			return "f:adminjsps/admin/message/list.jsp";
		}
		}
	/**
	 * 删除 
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String delete(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		/*
		 * 1. 获取参数:cid
		 * 2. 调用service方法，传递cid参数
		 *   > 如果抛出异常，保存异常信息，转发到msg.jsp显示
		 * 3. 调用findAll()
		 */
		String messageId = request.getParameter("messageId");
		System.out.println(messageId);
		try{
			seedService.messageDelete(messageId);
			return findAll(request, response);
		}catch(Exception e){
			request.setAttribute("msg",  e.getMessage());
			return "f:adminjsps/admin/message/list.jsp";
		}
		
		
		
	

	
	}
	public String findAll(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		/*
		 * 1. 调用service方法，得到所有分类
		 * 2. 保存到request域，转发到/adminjsps/admin/category/list.jsp
		 */
		
		request.setAttribute("message", seedService. listMessage());
		return "f:adminjsps/admin/message/list.jsp";
	}

}
